package judesart.app.repository;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import judesart.app.domain.Artist;
import judesart.app.domain.ArtistPhoto;
import judesart.app.domain.Image;
import judesart.app.shared.ValidationException;
import judesart.app.validation.AppValidator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class ArtistDAOImpl implements ArtistDAO {
    private final static Log LOGGER = LogFactory.getLog(ArtistDAOImpl.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Inject
    private AppValidator validator;

    @Inject
    private ImageDAO imageDAO;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Artist createArtist(Artist artist) throws ValidationException {
        validator.validate(artist);
        entityManager.persist(artist);
        entityManager.flush();
        return artist;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Artist findArtistByUserId(Long userId) {
        LOGGER.debug(" > findArtistByUserId ");
        try {
            Artist artist = (Artist) entityManager.createNamedQuery(
                    "Artist.findByUserId").setParameter("userId", userId).getSingleResult();
            artist.getAddress();
            artist.getProfile();
            LOGGER.debug(" artist.getPhotos().size() ["
                    + artist.getPhotos().size() + "]");
            for (ArtistPhoto photo : artist.getPhotos()) {

            }
            LOGGER.debug(" < findArtistByUserId : " + artist.getId());
            return artist;
        } catch (NoResultException e) {
            LOGGER.debug(" < findArtistByUserId : null");
            return null;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Artist addImageToArtist(Artist artist, String fileName,
            String blobKey) {
        Image image = new Image();
        image.setBlobKey(blobKey);
        image.setName(fileName);
        image = imageDAO.createImage(image);
        artist = entityManager.merge(artist);
        ArtistPhoto photo = new ArtistPhoto();
        photo.setArtist(artist);
        photo.setImageId(image.getId());
        if (artist.getPhotos() == null) {
            artist.setPhotos(new ArrayList<ArtistPhoto>());
        }
        artist.getPhotos().add(photo);
        entityManager.flush();
        return artist;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Artist deleteImageFromArtist(Artist artist, Long photoId) {
        Image image = imageDAO.deleteImage(photoId);
        if (image != null) {
            artist = entityManager.merge(artist);
            List<ArtistPhoto> photos = artist.getPhotos();
            ArtistPhoto found = null;
            for (ArtistPhoto photo : photos) {
                if (photo.getImageId().equals(photoId)) {
                    found = photo;
                    break;
                }
            }
            if (found != null) {
                artist.getPhotos().remove(found);
            }
            entityManager.flush();
        }
        return artist;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Artist updateArtist(Artist artist) throws ValidationException {
        validator.validate(artist);
        artist = entityManager.merge(artist);
        entityManager.flush();
        return artist;
    }

    @Override
    public Artist findArtistById(Long artistId) {
        return entityManager.find(Artist.class, artistId);
    }

}
